package com.toro.server;


import com.toro.config.Config;
import com.toro.message.RpcRequestMessage;
import com.toro.protocol.MessageCodecSharable;
import com.toro.protocol.ProcotolFrameDecoder;
import com.toro.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * @ClassName: ChatServer
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:12
 */
@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        //boss负责连接
        NioEventLoopGroup boss = new NioEventLoopGroup();
        //worker负责client
        NioEventLoopGroup worker = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcRequestMessageHandler RPC_HANDLER = new RpcRequestMessageHandler();
        //单位时间内如果没有接受到消息，认为断开连接
//        IdleStateHandler STATE_HANDLER = new IdleStateHandler(Config.getHeartListener(), 0, 0);
        HeartBeatServerHandler HEARTBEAT_HANDLER = new HeartBeatServerHandler();
        MyChannelDuplexHandler DUPLEX_HANDLER = new MyChannelDuplexHandler();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        QuitHandler QUIT_HANDLER = new QuitHandler();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //选择 服务器的 ServerSocketChannel 实现
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            // boss 负责处理连接 worker(child) 负责处理读写，决定了 worker(child) 能执行哪些操作（handler）
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    //粘包半包类优化
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    //日志
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    //编解码可sharable
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //RPC_HANDLER
//                    ch.pipeline().addLast(RPC_HANDLER);
                    //用来判断是不是读空闲时间过长或写空闲时间过长,规定时间未收到channel的数据
                    //int readerIdleTimeSeconds:为读超时时间（即多长时间没有接受到客户端发送数据）
                    //int writerIdleTimeSeconds:为写超时时间（即多长时间没有向客户端发送数据）
                    //int allIdleTimeSeconds):所有类型的超时时间
                    ch.pipeline().addLast(new IdleStateHandler(Config.getHeartListener(), 0, 0));
                    //全双工处理器出栈和入栈处理器 心跳监控
                    ch.pipeline().addLast(DUPLEX_HANDLER);
                    //接受心跳处理器
                    ch.pipeline().addLast(HEARTBEAT_HANDLER);
                    //登录管道处理器
                    ch.pipeline().addLast(LOGIN_HANDLER);
                    //发送消息处理器
                    ch.pipeline().addLast(CHAT_HANDLER);
                    //创建群处理器
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                    //加入群处理器
                    ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                    //获取群成员处理器
                    ch.pipeline().addLast(GROUP_MEMBERS_HANDLER);
                    //退出群聊处理器
                    ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                    //群消息发送处理器
                    ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                    //断开连接处理器
                    ch.pipeline().addLast(QUIT_HANDLER);
                }
            });
            //同步启动，非阻塞
            Channel channel = serverBootstrap.bind(Config.getServerPort()).sync().channel();
            log.info("服务器启动成功,监听端口：{}", Config.getServerPort());
            //同步关闭，非阻塞
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("服务器启动失败，原因：{}", e.getMessage());
        } finally {
            //优雅关闭
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            log.info("服务端关闭");
        }
        log.info("服务端程序结束");
    }
}
